const util = require('util')
const axios = require('axios')
const crypto = require('crypto')

class Wx {
    static async codeToToken(code) {
        const url = util.format(global.config.wx.loginUrl, global.config.wx.appId, global.config.wx.appSecret, code)
        const result = await axios.get(url)
    
        if (result.status !== 200) {
            throw new global.errs.AuthFailed('openid获取失败')
        }
        const errcode = result.data.errcode
        const errmsg = result.data.errmsg
        if (errcode) {
            throw new global.errs.AuthFailed('openid获取失败:' + errmsg)
        }
    
        // let user = await User.getUserByOpenid(result.data.openid)
        // if (!user) {
        //     user = await User.registerByOpenid(result.data.openid)
        // }
        // return generateToken(user.id, Auth.USER)
        return result.data
    }

    static async encryptedDataToken(encryptedData, iv, sessionKey) {

        const sessionKeyBuffer = new Buffer(sessionKey, 'base64')
        const encryptedDataBuffer = new Buffer(encryptedData, 'base64')
        const ivBuffer = new Buffer(iv, 'base64')

        try {
            // 解密
            let decipher = await crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer)
            // 设置自动 padding 为 true，删除填充补位
            await decipher.setAutoPadding(true)
            let decoded = await decipher.update(encryptedDataBuffer, 'binary', 'utf8')
            decoded += await decipher.final('utf8')
            
            decoded = JSON.parse(decoded)

            return decoded
        } catch (e) {
            throw new global.errs.AuthFailed('用户信息获取失败')
        }

    }
}
  
module.exports = {
    Wx
}
